#include "mytcpserver.h"
#include "../net/threadpool.h"
#include "../util/singleton.h"
#include "mytcpsocket.h"
MyTcpServer::MyTcpServer(QObject *parent) : QTcpServer(parent) {}

void MyTcpServer::incomingConnection(qintptr socketDescriptor) {
  MyTcpSocket *socket = new MyTcpSocket();
  socket->setSocketDescriptor(socketDescriptor);

  qDebug() << QString("[new connected]>> '%1:%2'")
                  .arg(socket->peerAddress().toString())
                  .arg(socket->peerPort());

  connect(socket, &MyTcpSocket::socketDisconnected, this,
          &MyTcpServer::socketDisconnectedSlot);

  connect(socket, &MyTcpSocket::sendData, this, &MyTcpServer::sendData);

  connect(this, &MyTcpServer::sendData, socket, &MyTcpSocket::sendDataSlot);

  auto thread = singleton<ThreadPool>::getInstance(this)->getThread();
  socket->setDB(thread->getDB());
  thread->add();
  socket->moveToThread(thread);
  qDebug() << QString("[Thread Loads]>> %1 socket(s) in thread'%2'")
                  .arg(thread->get_count())
                  .arg(thread->objectName());
}

void MyTcpServer::socketDisconnectedSlot(MyThread *th) {
  MyTcpSocket *socket = qobject_cast<MyTcpSocket *>(sender());
  qDebug() << QString("[disconnected]>> '%1:%2'")
                  .arg(socket->peerAddress().toString())
                  .arg(socket->peerPort());
  socket->close();
  socket->deleteLater();
  singleton<ThreadPool>::getInstance(this)->reduceThread(th);
}
